package com.woniu.defecttracking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.defecttracking.commens.ComUtil;
import com.woniu.defecttracking.dto.BugCountDto;
import com.woniu.defecttracking.dto.BugCountsDto;
import com.woniu.defecttracking.dto.BugInfoDto;
import com.woniu.defecttracking.dto.BugInfosDto;
import com.woniu.defecttracking.entity.*;
import com.woniu.defecttracking.exception.BugInfoException;
import com.woniu.defecttracking.mapper.BugInfoMapper;
import com.woniu.defecttracking.param.AddAndEditBugInfo;
import com.woniu.defecttracking.param.AllBugInfosParam;
import com.woniu.defecttracking.param.CloseBugParam;
import com.woniu.defecttracking.param.KoBugInfoParam;
import com.woniu.defecttracking.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiangle
 * @since 2021-12-31
 */
@Service
public class BugInfoServiceImpl extends ServiceImpl<BugInfoMapper, BugInfo> implements BugInfoService {
    @Autowired
    private BugTypeService bugTypeService;
    @Autowired
    private PriorityService priorityService;
    @Autowired
    private SavarityService savarityService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ProjectAccountService projectAccountService;

    @Override
    public boolean addOne(AddAndEditBugInfo addAndEditBugInfo) throws BugInfoException {
        BugInfo bugInfo = ComUtil.copyProperties(addAndEditBugInfo, BugInfo.class);
        bugInfo.setIsDelete(0);
        bugInfo.setBugState(0);
        //取登录人
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        bugInfo.setCreatePerson(principal.getAccountId());
        bugInfo.setCreateTime(ComUtil.nowDate());
        if (save(bugInfo))
            return true;
        else
            throw new BugInfoException("添加失败",411);
    }

    @Override
    public boolean editOne(AddAndEditBugInfo addAndEditBugInfo) throws BugInfoException {
        BugInfo bugInfo = ComUtil.copyProperties(addAndEditBugInfo, BugInfo.class);
        BugInfo byId = getById(bugInfo.getBugId());
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        byId.setModifyPerson(principal.getAccountId());
        byId.setModifyTime(ComUtil.nowDate());
        if (byId.getIsDelete()==1||byId.getBugState()!=0)
            throw new BugInfoException("修改失败",422);
        if (saveOrUpdate(bugInfo))
            return true;
        else
            throw new BugInfoException("修改失败",422);
    }

    @Override
    public boolean deleteOne(Integer id) throws BugInfoException {
        BugInfo byId = getById(id);
        if (byId==null||byId.getIsDelete()==1){
            throw new BugInfoException("没有该条目数据",1010);
        }
        if (byId.getBugState()!=0){
            throw new BugInfoException("该状态不能删除",1011);
        }
        byId.setIsDelete(1);

        boolean b = saveOrUpdate(byId);
        if (b)
            return b;
        throw new BugInfoException("删除失败",433);
    }

    @Override
    public boolean deletes(List<Integer> ids) throws BugInfoException {
        QueryWrapper<BugInfo> qw = new QueryWrapper<>();
        qw.in("bug_id",ids);
        List<BugInfo> list = list(qw);
        if (list.size()!=ids.size()){
            throw new BugInfoException("数据不同步，请先刷新页面",1013);
        }
        for (BugInfo bugInfo : list) {
            if (bugInfo.getBugState()!=0){
                throw new BugInfoException("包含有不能删除的条目",1012);
            }
            if (bugInfo.getIsDelete()==1){
                throw new BugInfoException("数据不同步，请先刷新页面",1013);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIsDelete(1);
        }
        boolean b = saveOrUpdateBatch(list);

        if (b)
            return true;
        throw new BugInfoException("删除失败",433);

    }

    @Override
    public BugInfoDto getOne(Integer id) {
        BugInfo byId = getById(id);
        BugInfoDto bugInfoDto = ComUtil.copyProperties(byId, BugInfoDto.class);
        BugInfosDto bugInfosDto = new BugInfosDto();
        ArrayList<BugInfoDto> dtos = new ArrayList<>();
        dtos.add(bugInfoDto);
        bugInfosDto.setBugs(dtos);
        BugInfosDto itName = getItName(bugInfosDto);
        return itName.getBugs().get(0);
    }

    @Override
    public BugInfosDto getAll(AllBugInfosParam allBugInfosParam) throws BugInfoException {


        QueryWrapper<BugInfo> queryWrapper = new QueryWrapper<>();
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer accountSupper = accountService.getById(principal.getAccountId()).getAccountSupper();

        if (accountSupper==0){
            List<Integer> projects = projectAccountService.getProjects(principal.getAccountId());
            if (projects.size()<=0){
                return new BugInfosDto();
            }
            queryWrapper.in("project_id",projects);
        }
        queryWrapper.ne("is_delete",1);
        if (allBugInfosParam.getProjectId()!=null){
            queryWrapper.eq("project_id",allBugInfosParam.getProjectId());
        }
        if (allBugInfosParam.getStatus()!=null){
            queryWrapper.eq("bug_state",allBugInfosParam.getStatus());
        }
        String startTime = allBugInfosParam.getStartTime();
        String endTime = allBugInfosParam.getEndTime();
        if (startTime!=null&&!startTime.trim().equals("")){
            queryWrapper.ge("plan_start_time",startTime);
        }
        if (endTime!=null&&!endTime.trim().equals("")){
            queryWrapper.le("plan_end_time",endTime);
        }
        if (startTime!=null&&!startTime.trim().equals("")&&endTime!=null&&!endTime.trim().equals("")){
            if (ComUtil.dataPanduan(startTime,endTime)) {
                throw new BugInfoException("时间选择错误");
            }
        }
        Long pageIndex = allBugInfosParam.getPageIndex();
        Long pageSize = allBugInfosParam.getPageSize();


        Page<BugInfo> ipage = new Page<>();
        ipage.setCurrent(pageIndex);
        ipage.setSize(pageSize);
        Page<BugInfo> page = page(ipage, queryWrapper);
        List<BugInfoDto> bugInfoDtos = ComUtil.copyList(page.getRecords(), BugInfoDto.class);
        BugInfosDto bugInfosDto = new BugInfosDto();
        bugInfosDto.setBugs(bugInfoDtos);
        bugInfosDto.setPageIndex(page.getCurrent());
        bugInfosDto.setTotal(page.getTotal());


        return getItName(bugInfosDto);
    }

    @Override
    public BugInfosDto getAllNew(AllBugInfosParam allBugInfosParam) throws BugInfoException {


        allBugInfosParam.setStatus(0);
        BugInfosDto all = getAll(allBugInfosParam);
        return getItName(all);
    }
    @Override
    public BugInfosDto getAllGo(AllBugInfosParam allBugInfosParam) throws BugInfoException {


        allBugInfosParam.setStatus(1);
        BugInfosDto all = getAll(allBugInfosParam);
        return getItName(all);
    }
    @Override
    public BugInfosDto getAllGoAndEnd(AllBugInfosParam allBugInfosParam) throws BugInfoException {

        QueryWrapper<BugInfo> queryWrapper = new QueryWrapper<>();
        //权限验证
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer accountSupper = accountService.getById(principal.getAccountId()).getAccountSupper();

        if (accountSupper==0){
            List<Integer> projects = projectAccountService.getProjects(principal.getAccountId());
            queryWrapper.in("project_id",projects);
        }



        queryWrapper.ne("is_delete",1);
        if (allBugInfosParam.getProjectId()!=null){
            queryWrapper.eq("project_id",allBugInfosParam.getProjectId());
        }
        Integer[] a = {1,2};
        queryWrapper.in("bug_state",a);
        String startTime = allBugInfosParam.getStartTime();
        String endTime = allBugInfosParam.getEndTime();
        if (startTime!=null&&!startTime.trim().equals("")){
            queryWrapper.ge("plan_start_time",startTime);
        }
        if (endTime!=null&&!endTime.trim().equals("")){
            queryWrapper.le("plan_end_time",endTime);
        }
        if (startTime!=null&&!startTime.trim().equals("")&&endTime!=null&&!endTime.trim().equals("")){
            if (ComUtil.dataPanduan(startTime,endTime)) {
                throw new BugInfoException("时间选择错误");
            }
        }
        Long pageIndex = allBugInfosParam.getPageIndex();
        Long pageSize = allBugInfosParam.getPageSize();

        Page<BugInfo> ipage = new Page<>();
        ipage.setCurrent(pageIndex);
        ipage.setSize(pageSize);
        Page<BugInfo> page = page(ipage, queryWrapper);
        List<BugInfoDto> bugInfoDtos = ComUtil.copyList(page.getRecords(), BugInfoDto.class);
        BugInfosDto bugInfosDto = new BugInfosDto();
        bugInfosDto.setBugs(bugInfoDtos);
        bugInfosDto.setPageIndex(page.getCurrent());
        bugInfosDto.setTotal(page.getTotal());

        return getItName(bugInfosDto);
    }
    @Override
    public BugInfosDto getAllKo(AllBugInfosParam allBugInfosParam) throws BugInfoException {
        //权限验证
        QueryWrapper<BugInfo> queryWrapper = new QueryWrapper<>();

        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer accountSupper = accountService.getById(principal.getAccountId()).getAccountSupper();

        if (accountSupper==0){
            List<Integer> projects = projectAccountService.getProjects(principal.getAccountId());
            queryWrapper.in("project_id",projects);
        }
        queryWrapper.ne("is_delete",1);
        if (allBugInfosParam.getProjectId()!=null){
            queryWrapper.eq("project_id",allBugInfosParam.getProjectId());
        }
        if (allBugInfosParam.getStatus()!=null){
            queryWrapper.eq("bug_state",1);
        }
        String startTime = allBugInfosParam.getStartTime();
        String endTime = allBugInfosParam.getEndTime();
        if (startTime!=null&&!startTime.trim().equals("")){
            queryWrapper.ge("plan_start_time",startTime);
        }
        if (endTime!=null&&!endTime.trim().equals("")){
            queryWrapper.le("plan_end_time",endTime);
        }
        if (startTime!=null&&!startTime.trim().equals("")&&endTime!=null&&!endTime.trim().equals("")){
            if (ComUtil.dataPanduan(startTime,endTime)) {
                throw new BugInfoException("时间选择错误");
            }
        }
        queryWrapper.eq("assignee",principal.getAccountId());
        Long pageIndex = allBugInfosParam.getPageIndex();
        Long pageSize = allBugInfosParam.getPageSize();

        Page<BugInfo> ipage = new Page<>();
        ipage.setCurrent(pageIndex);
        ipage.setSize(pageSize);
        Page<BugInfo> page = page(ipage, queryWrapper);
        List<BugInfoDto> bugInfoDtos = ComUtil.copyList(page.getRecords(), BugInfoDto.class);
        BugInfosDto bugInfosDto = new BugInfosDto();
        bugInfosDto.setBugs(bugInfoDtos);
        bugInfosDto.setPageIndex(page.getCurrent());
        bugInfosDto.setTotal(page.getTotal());
        return getItName(bugInfosDto);
    }

    @Override
    public boolean giveOne(AddAndEditBugInfo addAndEditBugInfo) throws BugInfoException {
        BugInfo byId = getById(addAndEditBugInfo.getBugId());
        if (addAndEditBugInfo.getAssignee()==null){
            throw new BugInfoException("分配失败",1014);
        }
        if (byId.getBugState()!=0){
            throw new BugInfoException("分配失败",1014);
        }
        byId.setBugState(1);
        byId.setAssignee(addAndEditBugInfo.getAssignee());
        byId.setAssignedTime(ComUtil.nowDate());
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        byId.setModifyPerson(principal.getAccountId());
        byId.setModifyTime(ComUtil.nowDate());
        saveOrUpdate(byId);
        return true;
    }

    //这个方法需要查询当前登录者
    @Override
    public boolean koBug(KoBugInfoParam koBugInfoParam) throws BugInfoException {
        BugInfo byId = getById(koBugInfoParam.getBugId());
        if (byId.getBugState()!=1){
            throw new BugInfoException("无法处理",1015);
        }
        byId.setModifyTime(koBugInfoParam.getModifyTime());
        //这里查询当前登录人信息，替换1
        AccountDetails principal = (AccountDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        byId.setModifyPerson(principal.getAccountId());
        byId.setBugState(koBugInfoParam.getBugState());
        byId.setActWorkHours(koBugInfoParam.getActWorkHours());
        byId.setDoneRatio(koBugInfoParam.getDoneRatio());
        saveOrUpdate(byId);
        return true;
    }

    @Override
    public boolean closeBug(CloseBugParam closeBugParam) {
        BugInfo byId = getById(closeBugParam.getBugId());
        byId.setBugState(closeBugParam.getBugState());
        byId.setModifyTime(ComUtil.nowDate());
        saveOrUpdate(byId);
        return true;
    }

    @Override
    public BugCountsDto bugTypeCount(AllBugInfosParam allBugInfosParam) throws BugInfoException {
        List<BugInfo> count = count(allBugInfosParam);
        BugCountsDto bugCountsDto = new BugCountsDto();
        if (count==null||count.size()<=0)
            throw new BugInfoException("没有数据",1010);
        Map<Integer,Integer> cc = new HashMap<>();

        for (BugInfo bugInfo : count) {
            System.out.println(cc.get(bugInfo.getBugTypeId()));
            if (cc.get(bugInfo.getBugTypeId())!=null){
                cc.put(bugInfo.getBugTypeId(),cc.get(bugInfo.getBugTypeId())+1);
            }else {
                cc.put(bugInfo.getBugTypeId(),1);
            }

        }
        List<BugType> list = bugTypeService.list();
        Map<Integer,String> bugtypes = new HashMap<>();
        for (BugType bugType : list) {
            bugtypes.put(bugType.getBugTypeId(),bugType.getBugTypeName());
        }

        List<BugCountDto> bugCountDtos = new ArrayList<>();

        Set<Integer> integers = cc.keySet();
        for (Integer integer : integers) {
            bugCountDtos.add(new BugCountDto(bugtypes.get(integer),cc.get(integer)));
        }

        bugCountsDto.setStatistics(bugCountDtos);


        return bugCountsDto;
    }

    @Override
    public BugCountsDto savarityCount(AllBugInfosParam allBugInfosParam) throws BugInfoException {
        List<BugInfo> count = count(allBugInfosParam);
        BugCountsDto bugCountsDto = new BugCountsDto();
        if (count==null||count.size()<=0)
            throw new BugInfoException("没有数据",1010);
        Map<Integer,Integer> cc = new HashMap<>();
        for (BugInfo bugInfo : count) {
            if (cc.get(bugInfo.getSavarityId())!=null){
                cc.put(bugInfo.getSavarityId(),cc.get(bugInfo.getSavarityId())+1);
            }else{
                cc.put(bugInfo.getSavarityId(),1);
            }
        }
        List<Savarity> list = savarityService.list();
        Map<Integer,String> bugtypes = new HashMap<>();
        for (Savarity bugType : list) {
            bugtypes.put(bugType.getSavarityId(),bugType.getSavarityLev());
        }


        Set<Integer> integers = cc.keySet();
        List<BugCountDto> bugCountDtos = new ArrayList<>();
        for (Integer integer : integers) {
            bugCountDtos.add(new BugCountDto(bugtypes.get(integer),cc.get(integer)));
        }

        bugCountsDto.setStatistics(bugCountDtos);
        return bugCountsDto;
    }

    @Override
    public BugCountsDto priorityCount(AllBugInfosParam allBugInfosParam) throws BugInfoException {
        List<BugInfo> count = count(allBugInfosParam);
        BugCountsDto bugCountsDto = new BugCountsDto();
        if (count==null||count.size()<=0)
            throw new BugInfoException("没有数据",1010);
        Map<Integer,Integer> cc = new HashMap<>();
        for (BugInfo bugInfo : count) {
            if (cc.get(bugInfo.getBugState())!=null){
                cc.put(bugInfo.getBugState(),cc.get(bugInfo.getBugState())+1);
            }else{
                cc.put(bugInfo.getBugState(),1);
            }
        }

        Map<Integer,String> bugtypes = new HashMap<>();
        bugtypes.put(0,"新建");
        bugtypes.put(1,"进行中");
        bugtypes.put(2,"已解决");
        bugtypes.put(3,"关闭");

        Set<Integer> integers = cc.keySet();
        List<BugCountDto> bugCountDtos = new ArrayList<>();
        for (Integer integer : integers) {
            bugCountDtos.add(new BugCountDto(bugtypes.get(integer),cc.get(integer)));
        }

        bugCountsDto.setStatistics(bugCountDtos);
        return bugCountsDto;
    }

    public List<BugInfo> count(AllBugInfosParam allBugInfosParam) throws BugInfoException {
        QueryWrapper<BugInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_delete",1);

        if (allBugInfosParam.getProjectId()!=null){
            queryWrapper.eq("project_id",allBugInfosParam.getProjectId());
        }

        String startTime = allBugInfosParam.getStartTime();
        String endTime = allBugInfosParam.getEndTime();
        if (startTime!=null&&!startTime.trim().equals("")){
            queryWrapper.ge("plan_start_time",startTime);
        }
        if (endTime!=null&&!endTime.trim().equals("")){
            queryWrapper.le("plan_end_time",endTime);
        }
        if (startTime!=null&&!startTime.trim().equals("")&&endTime!=null&&!endTime.trim().equals("")){
            if (ComUtil.dataPanduan(startTime,endTime)) {
                throw new BugInfoException("时间选择错误");
            }
        }
        List<BugInfo> list = list(queryWrapper);



        return list;
    }

    public BugInfosDto getItName(BugInfosDto bugInfosDto){
        List<BugInfoDto> bugs = bugInfosDto.getBugs();
        if (bugs.size()<=0){
            return bugInfosDto;
        }
        List<Integer> collect = bugs.stream().map(a -> a.getBugTypeId()).collect(Collectors.toList());
        List<BugType> bugTypes = bugTypeService.listByIds(collect);
        ComUtil.listAddByFields(bugs,bugTypes,"bugTypeId",Integer.class);
        List<Integer> collect2 = bugs.stream().map(a -> a.getPriorityId()).collect(Collectors.toList());
        List<Priority> priorities = priorityService.listByIds(collect2);
        ComUtil.listAddByFields(bugs,priorities,"priorityId",Integer.class);
        List<Integer> collect3 = bugs.stream().map(a -> a.getSavarityId()).collect(Collectors.toList());
        List<Savarity> savarities = savarityService.listByIds(collect3);
        ComUtil.listAddByFields(bugs,savarities,"savarityId",Integer.class);


        List<Integer> ps = bugs.stream().map(a -> a.getProjectId()).collect(Collectors.toList());
        List<Project> projects = projectService.listByIds(ps);
        ComUtil.listAddByFields(bugs,projects,"projectId",Integer.class);
        bugInfosDto.setBugs(bugs);
        return bugInfosDto;
    }


}
